package com.itheima.reggie.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.JwtUtil;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Map;

/**
 * @Author Yang
 * @Date 2023/3/8 12:03
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    //发送短信
    @Override
    public void sendMsg(String phone) {
        String code = RandomUtil.randomNumbers(6);
        code = "123";
        log.info("下发成功: {}" , code);

        //阿里云发送验证码
//        smsTemplate.sendSms(phone,code);

        //储存到redis数据库
        redisTemplate.opsForValue().set(Constant.USER_CODE + phone, code, Duration.ofSeconds(300));
        log.info("储存到 redis 数据库");
    }


    //接收手机号和验证码
    @Override
    public String login(String phone, String code) {
        // 1.校验验证码
        // 1-1 取出redis中验证码
        String codeRedis = (String) redisTemplate.opsForValue().get(Constant.USER_CODE + phone);
        // 1-2 比较
        if (!StrUtil.equals(codeRedis, code)) {
            throw new CustomException("验证码错误");
        }
        //验证码正确
        // 2.根据phone查询数据库  select * from user where phone = ?
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getPhone, phone);
        User user = userMapper.selectOne(qw);
        // 3.没查到，创建新用户
        if (user == null) {
            User user1 = new User();
            user1.setPhone(phone);
            user1.setStatus(1);
            //保存到数据库
            userMapper.insert(user1);
        }

        // 4.根据user，制作token
        Map<String, Object> map = BeanUtil.beanToMap(user);
        String token = JwtUtil.createToken(map);

        // 5.删除redis验证码
        redisTemplate.delete(Constant.USER_CODE + phone);

        // 6.返回token
        return token;
    }
}
